package atlantik.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JPanel;

import modelz.AbstractUpdateableCollectionListener;
import atlantik.game.Atlantik;
import atlantik.game.AtlantikState;
import atlantik.game.Detail;
import atlantik.game.DetailAction;

class DetailsView extends JPanel {

	private static final long serialVersionUID = 6009335074727417445L;

	private final JEditorPane details = new JEditorPane();

	private final JPanel actions = new JPanel();

	private final Map<DetailAction, JButton> actionPeers = new HashMap<DetailAction, JButton>();

	private final StringBuffer text = new StringBuffer();

	public DetailsView(Atlantik client) {
		actions.setLayout(new FlowLayout(FlowLayout.RIGHT));
		setLayout(new BorderLayout());

		details.setEditable(false);
		details.setContentType("text/html");
		add(details, BorderLayout.CENTER);
		add(actions, BorderLayout.SOUTH);

		AtlantikState state = client.getState();
		state.details().addListener(new DetailListener());
		state.details().actions().addListener(new DetailActionListener());
	}

	public Dimension getPreferredSize() {
		return new Dimension(0, 0);
	}

	private class DetailListener extends AbstractUpdateableCollectionListener<Detail> {
		public void added(Detail detail) {
			if (detail.getEstate() != null)
				text
						.append(String.format("%s: ", detail.getEstate()
								.getName()));
			text.append(detail.getText() + "<br>");
			details.setText(String.format("<html><body>%s</body></html>", text
					.toString()));
			details.setText(text.toString());
		}

		public void cleared() {
			text.delete(0, text.length());
			details.setText("");
		}
	}

	private class DetailActionListener extends AbstractUpdateableCollectionListener<DetailAction> {
		public void added(final DetailAction action) {
			JButton button = new JButton(new ClientAction<DetailAction>(action));
			actions.add(button);
			actionPeers.put(action, button);
			revalidate();
		}

		public void cleared() {
			// TODO let this get handled by a PeerMap
			for( Iterator<DetailAction> i = actionPeers.keySet().iterator(); i.hasNext(); ) {
				DetailAction action = i.next();
				JButton button = actionPeers.get(action);
				actions.remove(button);
				i.remove();
			}
			revalidate();
		}
	}

}
